package cn.myfirefly.core;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseDao<T> {
	
	@Autowired
	protected SessionFactory sessionFactory;
	
	private Class<T> cls = null;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public BaseDao() {
		// 为了得到T的Class，采用如下方法
		// 1得到该泛型类的子类对象的Class对象
		Class clz = this.getClass();
		// 2得到子类对象的泛型父类类型（也就是BaseDao<T>）
		ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
		
		Type[] types = type.getActualTypeArguments();

		cls = (Class<T>) types[0];
	}
	
	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public Integer save(T t) {
		Session session = sessionFactory.getCurrentSession();
		return (Integer)session.save(t);
	}
	
	@SuppressWarnings("unchecked")
	public T get(Integer sn) {
		Session session = sessionFactory.getCurrentSession();
		return (T)session.get(cls, sn);
	}
	
	public void del(T t) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(t);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByExample(T t) {
		Session session = sessionFactory.getCurrentSession();
		List<T> results = session.createCriteria(cls).add(Example.create(t)).list();
		return results;
	}
}
